package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;



public class Server {
    private ServerSocket serverSocket;
    private static final Integer PORT = 4545;
    private List<PrintWriter> allOut = new ArrayList<>();
    private List<String> onlineUsers=new ArrayList<>();
    //1.私有化集合保存所有用户名--onlineUsers
    private Map<String, String> userDataBase;

    public Server () {
        try {
            serverSocket = new ServerSocket(PORT);
            userDataBase = new HashMap<>();
            userDataBase.put("宇航员", "123456");
            userDataBase.put("丁丁", "123456");
        } catch (BindException e) {
            System.out.println("端口号重复创建....");
        } catch (IOException e) {
            System.out.println("申请端口号失败");
        }
    }

    public void start(){
        try {
            while(true){
                        System.out.println("----等待客户端连接----");
                        Socket socket = serverSocket.accept();
                    new Thread(new ClientHandler(socket)).start();
                    }
        } catch (IOException e) {
            System.out.println("服务器端通讯断开了");
        }finally {
            if(serverSocket!=null&&serverSocket.isClosed()){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
            }

        }
    }

    public static void main(String[] args)  {
        new Server().start();
    }
    private boolean Login(String user,String pass){
        return userDataBase.containsKey(user)&&userDataBase.get(user).equals(pass);
    }
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;
        private String username;
        private String password;



        public ClientHandler(Socket s){
            this.socket=s;
            ip=socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);
                synchronized (allOut){
                    allOut.add(pw);
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接了");
            }
        }

    private synchronized void broadcastMessage(String message){
        for (PrintWriter pw:allOut){
            pw.println("消息广播："+message);
        }
    }
    //2.封装方法：同步转发给所有客户端消息：“在线用户：”+onlineUsers
    //updateOnlineUsers 更新在线人数名单的方法：”在线用户：“+onlineUsers
    //字符串：String userList=”在线用户“+String.join("、",onlineUsers)
    //userList 写出给所有客户端
    private synchronized void updateOnlineUsers(){
        synchronized (onlineUsers){
            String userList="在线用户："+String.join("、",onlineUsers);
            broadcastMessage("用户名消息"+userList);
        }
    }
        private void handleChat() {
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(ip + "服务器端说：" + message);

                        System.out.println("服务器端请输入：");

                        broadcastMessage(message);
                        updateOnlineUsers();
                        System.out.println("服务器端请输入：");

                    }
                } catch (IOException e) {
                    System.out.println();
                }
            }).start();
            System.out.println("输入文字内容：");
            Scanner input = new Scanner(System.in);
            while (true) {
                String say = input.nextLine();
                pw.println("服务器端说：" + say);
                System.out.println("服务器端输入：");
                if (say.equalsIgnoreCase("exit")){
                    System.exit(0);
                }
            }
        }
        public void run() {
            try {
                pw.println("请输入用户名：");
                username=br.readLine();
                pw.println("请输入密码：");
                password=br.readLine();
                if (Login(username,password)){
                    pw.println("登录成功  欢迎进入皮皮牌聊天室");
                    synchronized (onlineUsers){
                        onlineUsers.add(username);
                        System.out.println(username+"连接成功");
                        updateOnlineUsers();
                    }
                    //3.判断客户端链接成功---加入集合中   3.1【同步块：监视对象---集合】
                    //3.2  客户端登录成功--名字加入集合中    方法
                    handleChat();
                }else {
                    pw.println("登录失败 用户名或者密码错误");
                    socket.close();   //关闭
                }

            }catch (IOException e){
                System.out.println("服务器端读写出问题");
            } finally {
                //4.同步块---从集合中依次移除用户名
                synchronized (allOut){  //目的：移除 刚刚链接的客户端
                    //理解：一个客户端已经转发完毕了  移除当前客户端的写出功能
                    allOut.remove(pw);
                }
                synchronized (onlineUsers){
                    onlineUsers.remove(username);
                }
                if (pw!=null)
                    pw.close();
                if (br != null)
                    try {
                        br.close();
                    }catch (IOException e){
                        System.out.println();
                    }

                if (socket!=null&&!socket.isClosed()){
                    System.out.println(ip+"一个客户端退出服务器连接");
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(ip+"一个客户端退出链接异常");
                    }
                }

            }
        }
    }
}